//
//  DMCCycleImages.m
//  16-UICollectionViewCycleImage
//
//  Created by dllo on 16/8/4.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "DMCCycleImages.h"
#import "UIImageView+DownloadImage.h"
#import "FirstTopimg.h"
#import "FirstData.h"
#import "FirstDatax.h"
#import "UIImageView+WebCache.h"
#import "DetailsViewController.h"
#define kCollectionViewCellReuse @"reuseCycle"
#define kWidth self.bounds.size.width
#define kHeight self.bounds.size.height
@interface DMCCycleImages ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *cycleCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, copy) DidSelectItemAtIndexPath indexPath;

@end

@implementation DMCCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
        
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
       self.backgroundColor = [UIColor redColor];
        [self setUp];
        
           }
    return self;
}

#pragma mark - 实现block协议
- (void)didSelectItemAtIndexPath:(DidSelectItemAtIndexPath)index {
    self.indexPath = index;
}
- (void)setUp {
    [self createCollectionView];
    [self createPageControl];
    [self createTimer];
}
#pragma mark - CreateCollectionView
// 处理对象
- (void)createCollectionView {
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: _layout];
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;

    [_cycleCollectionView registerClass:[CDMCycleImageCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
    
    _cycleCollectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:_cycleCollectionView];
    _cycleCollectionView.backgroundColor = [UIColor whiteColor];
    
    
}

- (void)setTopimg:(NSMutableArray<FirstTopimg *> *)topimg {
    _topimg = topimg;
    id first = _topimg.firstObject;
    id last = _topimg.lastObject;
    [_topimg addObject:first];
    [_topimg insertObject:last atIndex:0];
    [_cycleCollectionView reloadData];
}
#pragma mark - CollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    _pageControl.numberOfPages = _topimg.count - 2;
    return _topimg.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CDMCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
//     网络请求图片

    [cell.cycleImage sd_setImageWithURL:[NSURL URLWithString:self.topimg[indexPath.row].pic] placeholderImage:[UIImage imageNamed:@"project_bg_detail"]];
    // 本地图片
//    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    
    
    return cell;
}
#pragma mark - CreatePageControl
- (void)createPageControl {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self.pageControl addTarget:self action:@selector(pageControl:) forControlEvents:UIControlEventValueChanged];

    [self addSubview:_pageControl];

}
- (void)pageControl:(UIPageControl *)page {
    [self.cycleCollectionView setContentOffset:CGPointMake(CGRectGetWidth(self.cycleCollectionView.bounds) * page.currentPage, 0) animated:YES];
}
#pragma mark - CreateTimer 
- (void)createTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    self.timer = timer;
}
- (void)nextPage {
    CGFloat totaloffset = _cycleCollectionView.contentOffset.x + self.bounds.size.width;
    [_cycleCollectionView setContentOffset:CGPointMake(totaloffset, 0) animated:YES];
    if (totaloffset == (_topimg.count - 1) * self.bounds.size.width) {
        _cycleCollectionView.contentOffset = CGPointZero;
    }
    _pageControl.currentPage = (_cycleCollectionView.contentOffset.x + self.bounds.size.width) / self.bounds.size.width - 1;
}
- (void)removeTimer {
    // 取消timer
    [self.timer invalidate];
    self.timer = nil;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _cycleCollectionView.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(kWidth, 0) animated:YES];
    
    _pageControl.frame = CGRectMake(0, 0, 100, 20);
    _pageControl.center = CGPointMake(kWidth / 2, kHeight - 20);
    
    
    _label.frame = CGRectMake(0, 0, kWidth, 50);
    _label.center = CGPointMake(kWidth / 2, 20);
    
    
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self createTimer];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   //#warning 直接判断等与0有啥问题
    if (scrollView.contentOffset.x <= _cycleCollectionView.bounds.size.width / 500) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:(_topimg.count - 2) inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        
    } else if (scrollView.contentOffset.x > _cycleCollectionView.bounds.size.width * (_topimg.count - 1) - 1) {
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = (scrollView.contentOffset.x - self.cycleCollectionView.bounds.size.width) / _cycleCollectionView.bounds.size.width;
    
}
#pragma mark - 轮播图的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // block传参
//    NSLog(@"点了第%ld张", indexPath.row);
    self.indexPath(indexPath);
}


@end
#pragma mark - CollectionViewCell
@implementation CDMCycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
            }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
       
}

@end
